package com.yougou;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.yougou.base.BaseActivity;
import com.yougou.ui.cart.CartFragment;
import com.yougou.ui.category.CategoryFragment;
import com.yougou.ui.home.HomeFragment;
import com.yougou.ui.mine.MineFragment;

public class MainActivity extends BaseActivity {
    
    private BottomNavigationView mBottomNavigation;
    private Fragment mCurrentFragment;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }
    
    @Override
    protected void initView() {
        mBottomNavigation = findViewById(R.id.bottom_navigation);
        
        mBottomNavigation.setLabelVisibilityMode(1);
        // 设置默认显示首页
        showFragment(new HomeFragment());
        
        // 设置底部导航点击事件
        mBottomNavigation.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.nav_home) {
                showFragment(new HomeFragment());
                return true;
            } else if (itemId == R.id.nav_category) {
                showFragment(new CategoryFragment());
                return true;
            } else if (itemId == R.id.nav_cart) {
                showFragment(new CartFragment());
                return true;
            } else if (itemId == R.id.nav_mine) {
                showFragment(new MineFragment());
                return true;
            }
            return false;
        });
    }
    
    @Override
    protected void initData() {
        // MainActivity不需要初始化数据
    }
    
    
    private void showFragment(Fragment fragment) {
        if (mCurrentFragment == fragment) {
            return;
        }
        
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        
        if (mCurrentFragment != null) {
            transaction.hide(mCurrentFragment);
        }
        
        mCurrentFragment = fragment;
        
        if (!fragment.isAdded()) {
            transaction.add(R.id.fragment_container, fragment);
        } else {
            transaction.show(fragment);
        }
        
        transaction.commit();
    }
}
